package com.ok.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ok.api.client.IntegralClient;
import com.ok.api.domain.dto.OkIntegralDetailDTO;
import com.ok.common.config.IntegralNum;
import com.ok.common.utils.SnowflakeIdWorker;
import com.ok.common.utils.UserContext;
import com.ok.community.domain.dto.OkCommentDto;
import com.ok.community.domain.po.OkCard;
import com.ok.community.domain.po.OkComment;
import com.ok.community.mapper.OkCommentMapper;
import com.ok.community.service.IOkCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 评论 服务实现类
 * </p>
 *
 * @author lhw
 * @since 2024-05-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OkCommentServiceImpl extends ServiceImpl<OkCommentMapper, OkComment> implements IOkCommentService {

    private final IntegralClient integralClient;
    private final RabbitTemplate rabbitTemplate;

    @Override
    @GlobalTransactional
    public void addComment(OkCommentDto okCommentDto) {
        OkComment okComment = new OkComment();
        BeanUtils.copyProperties(okCommentDto,okComment);

        okComment.setUserId(UserContext.getUser());
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
        long fid = idWorker.nextId();
        okComment.setSnowflakeId(fid);
        //向评论表中添加数据
        this.save(okComment);

        //修改用户积分
        integralClient.update(IntegralNum.INTEGRAL_COMMENT_ADD);

        //根据雪花id的到评论对象
        LambdaQueryWrapper<OkComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OkComment::getSnowflakeId,fid);
        OkComment comment = this.getOne(wrapper);
        log.info("评论信息:{}",comment);
        //构建积分详细对象
        OkIntegralDetailDTO detailDTO = new OkIntegralDetailDTO();
        detailDTO.setUserId(UserContext.getUser());
        detailDTO.setIntegral(IntegralNum.INTEGRAL_COMMENT_ADD);
        detailDTO.setCommentId(comment.getId());

        //发送消息添加积分详细
        try {
            rabbitTemplate.convertAndSend("integral_direct","",detailDTO);
        } catch (AmqpException e) {
            log.error("发送消息添加积分详细失败：{}",e.getMessage());
        }
    }
}
